import { mapGetters } from 'vuex'
import { getSceneCouponConfig, getSceneCouponDetail, getSceneCouponDetailByIds, useSceneCoupon } from '@/api/coupon'
import { getUserActivity, getPrdoductDetail } from '@/api/common'
// import { getLocalStorage, setLocalStorage } from '@/utils/storage'

export default {
  computed: {
    ...mapGetters(['appInfo', 'hasPay', 'hasLogin', 'userInfo']),
    _isUnlimitVIP () { // 终身vip
      if (this.navActive === 'energy') return false
      if (this.pkgId) { // 在完整版里面，存在多个权益，使用pkgId变量区分
        return Boolean(this.userInfo?.is_member && this.userInfo?.buy_right_package?.find(item => item.pkg_id === this.pkg_id)?.unlimited)
      } else { // 独立里面，只有一个权益
        return Boolean(this.userInfo?.is_member && this.userInfo?.buy_right_package?.length && this.userInfo.buy_right_package[0].unlimited)
      }
    }
  },
  data: () => {
    return {
      // pkgId: '40000',
      sceneCouponBeforePayCloseCouponId: null,
      seckillCouponInfo: null,
      seckillCouponConfig: { list: [] }
    }
  },
  watch: {
    hasLogin: { // 登录切换，重新请求数据
      handler (value) {
        if (value) {
          this._getCouponConfigData()
        }
      }
    }
  },
  created () {
    this.closeStorageName = '_scene_coupon_seckill_before_pay_close_' + (this.pkgId || '')

    this.seckillCouponCfgMap = {}
    this.$xzReg('inform_close', async () => {
      if (!window.navigator.onLine) {
        this._closeWindow()
        return
      }
      if (this.navActive === 'energy') {
        this.seckillCouponConfig = this.seckillCouponCfgMap['jgb'] || { list: [] }
        this.closeStorageName = '_scene_coupon_seckill_close_before-buyJGB_'
      } else {
        this.seckillCouponConfig = this.seckillCouponCfgMap['vip'] || { list: [] }
        this.closeStorageName = '_scene_coupon_seckill_before_pay_close_' + (this.pkgId || '')
      }

      let count = this.getStorageClose().count
      count++
      this.setStorageClose({ count })
      if (!this._isUnlimitVIP && this.detectSeckilScence(count)) {
        this._sceneCouponDialog()
      } else {
        this._closeWindow()
      }
    })
    this._getCouponConfigData()
  },

  methods: {
    async _sceneCouponDialog () {
      this.$xz('xz_substat_action', this.seckillCouponInfo.exhibit_id)
      if (this.seckillCouponInfo.type === 'coupon') {
        this.$DiyDialog('sceneSeckillDialog', {
          dialogVisible: false,
          windowName: this.windowName
        })

        this.$DiyDialog('sceneCouponDialog', {
          dialogVisible: true,
          info: this.seckillCouponInfo
        }).then(async () => {
          const seckill_ids = String(this.seckillCouponInfo.seckill_id).split(',').map(id => Number(id))
          await useSceneCoupon({
            coupon_id: seckill_ids
          })
          this.$PsMessage({ message: '您已领取成功，请尽快使用' })
          this.$eventBus.$emit('scene-coupon-select', seckill_ids[0])
          this._getCouponConfigData()
        }).catch(() => {
          this._closeWindow()
        })
      } else {
        this.$DiyDialog('sceneCouponDialog', { dialogVisible: false })

        this.$DiyDialog('sceneSeckillDialog', {
          dialogVisible: true,
          info: this.seckillCouponInfo,
          windowName: this.windowName
        }).then(async () => {
          // this._getCouponConfigData()
          this._closeWindow()
        }).catch(() => {
          this._closeWindow()
        })
      }
    },
    _closeWindow () {
      this.$xz('xz_switch_dialog', this.windowName, false)
    },
    async _getCouponConfigData () {
      if (!this.hasLogin) return

      const rs = await getSceneCouponConfig({
        app_id: this.appInfo.appID,
        version: this.appInfo.version,
        union_id: this.appInfo.channel,
        keyname: 'cjqhms'
      })
      if (!rs?.data?.params?.length) return

      const scene = rs.data.params.filter(v => v.scene.includes('close_before-buyVIP'))[0] || {}
      const jgbScene = !this.showEnergy ? null : rs.data.params.filter(v => v.scene.includes('close_before-buyJGB'))[0]
      let list = scene?.list || []
      if (jgbScene?.list) {
        list = list.concat(jgbScene.list)
      }
      if (!list.length) return

      await list.map(async item => {
        try {
          if (!item.detail) {
            item.detail = await this._getDetail(item)
          }
          if (item.detail?.product_ids?.length && !item.product) {
            const res = await getPrdoductDetail({ id: item.detail.product_ids[0] })
            item.product = res.data
          }
        } catch (error) {}

        this.preloadSekillImage(item.background_image)
      })
      this.seckillCouponCfgMap = {
        'vip': scene,
        'jgb': jgbScene
      }
      // this.seckillCouponConfig = {
      //   ...scene,
      //   list
      // }
      // console.log(this.seckillCouponConfig)
    },
    detectSeckilScence (count) {
      // 用户未登录
      if (!this.hasLogin) return false
      // 已付款不弹
      if ((this.navActive === 'energy' && this.hasPayEnergy) || this.hasPayRight) return false
      const targetCount = this.getTargetCount(count)
      if (targetCount === -1) return false

      const list = this.seckillCouponConfig.list || []
      const targetSeckil = list.find?.(v => v.count === targetCount)

      this.setStorageClose({ show: Date.now(), count: targetCount })
      const showtimes = this.getStorageClose().show + 1
      this.setStorageClose({ show: showtimes })
      // if (!targetSeckil || !targetSeckil.detail) return false
      // const total = localStorage.getItem('_scene_coupon_seckill_total_' + targetSeckil.seckill_id) || 0
      // localStorage.setItem('_scene_coupon_seckill_total_' + targetSeckil.seckill_id, total + 1)
      this.seckillCouponInfo = targetSeckil
      return true
    },
    getTargetCount (count) {
      const list = this.seckillCouponConfig.list || []
      let maxCount = 0
      for (let i = 0; i < list.length; i++) {
        if (list[i].count > maxCount) {
          maxCount = list[i].count
        }
        // const total = localStorage.getItem('_scene_coupon_seckill_total_' + list[i].seckill_id) || 0
        // if (list[i].count === count && list[i].detail && this._isPkgIdSame() && total < list[i].total) {
        if (list[i].count === count && list[i].detail && this._isPkgIdSame(list[i])) {
          return count
        }
        // if (!list[i].detail) {
        //   localStorage.removeItem('_scene_coupon_seckill_total_' + list[i].seckill_id)
        // }
      }
      if (count < maxCount) {
        return this.getTargetCount(count + 1)
      }
      return -1
    },
    // 判断当前权益包类型是否符合
    _isPkgIdSame (row) {
      if (!this.pkgId) {
        return true
      }
      if (row.type === 'coupon' && row.detail?.pkg_id && !row.detail.pkg_id.includes(this.pkgId)) {
        return false
      }
      if (row.type === 'seckill' && row.product?.related_pkg_detail?.length && row.product.related_pkg_detail[0].pkg_id !== this.pkgId) {
        return false
      }
      return true
    },
    getStorageClose () {
      const val = localStorage.getItem(this.closeStorageName)
      let data = { time: 0, count: 0, show: 0 }
      try {
        data = JSON.parse(val)
      } catch (e) {
      }
      data = data || { time: 0, count: 0, show: 0 }
      // 超过间隔小时，重置次数
      const interval_reset = this.seckillCouponConfig.interval_reset
      if (data.show === 0 || interval_reset === 0 || (interval_reset && data.show && (Date.now() - data.show > interval_reset * 60 * 60 * 1000))) {
        data = { time: 0, count: 0, show: 0 }
      }
      return data
    },
    setStorageClose ({ count, show } = {}) {
      const data = this.getStorageClose()
      data.count = count || data.count
      data.time = Date.now()
      data.show = show || data.show
      localStorage.setItem(this.closeStorageName, JSON.stringify(data))
    },
    // 预加载背景
    preloadSekillImage (img) {
      if (!img) return
      const imgEl = new Image()
      imgEl.src = img
      imgEl.onload = () => {}
    },
    async _getDetail (row) {
      const seckill_ids = String(row.seckill_id).split(',')
      let detail = null
      if (seckill_ids.length > 1 && row.type === 'coupon') {
        detail = await getSceneCouponDetailByIds(seckill_ids).then(res => res).catch((err) => err)
      } else {
        detail = row.type === 'coupon' ? await this._getSceneCouponDetail(row.seckill_id) : await this._getActivityDetail(row.seckill_id)
      }
      return detail
    },
    async _getSceneCouponDetail (coupon_id) {
      let detail = null
      const rs = await getSceneCouponDetail({ coupon_id })
      if (['ok', 'draw_valid'].includes(rs.data.sub_code) && rs.data.detail) {
        detail = { ...rs.data.detail }
      }
      return detail
    },
    async _getActivityDetail (act_id) {
      let detail = null
      const rs = await getUserActivity({ act_id })
      if (rs.data.sub_code === 'not_join' && rs.data.act_info) {
        detail = { ...rs.data.act_info }
      }
      return detail
    }
  }
}
